package com.rentong.wx.cust.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.rentong.wx.cust.dao.CustGuanzhuDao;
import com.rentong.wx.cust.domain.CustGuanzhuEntity;
import com.rentong.wx.cust.dto.CustGuanzhuDto;
import com.rentong.wx.cust.dto.CustGuanzhuVo;
import com.rentong.wx.cust.service.CustGuanzhuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class CustGuanzhuServiceImpl implements CustGuanzhuService {

    @Resource
    private CustGuanzhuDao custGuanzhuDao;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<CustGuanzhuVo> getCustGuanzhuList(Integer type, Long custId) {
        List<CustGuanzhuVo> custGuanzhuVoList = custGuanzhuDao.getCustGuanzhuList(type, custId);
        if (type == 2) {
            //我的粉丝中我是否己关注
            List<Long> ids = custGuanzhuVoList.stream().map(CustGuanzhuVo::getCustId).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(ids)) {
                List<CustGuanzhuEntity> guanzhuEntities = custGuanzhuDao.getCustGuanZhuByCustidAndCid(custId, ids);
                Set<Long> guanzhuEntityCustIds = guanzhuEntities.stream()
                        .map(CustGuanzhuEntity::getCId)
                        .collect(Collectors.toSet());

                for (CustGuanzhuVo custGuanzhuVo : custGuanzhuVoList) {
                    if (guanzhuEntityCustIds.contains(custGuanzhuVo.getCustId())) {
                        custGuanzhuVo.setType(2);
                    } else {
                        custGuanzhuVo.setType(1);
                    }
                }
            }
        }
        return custGuanzhuVoList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void custGuanzhu(Long custId, CustGuanzhuDto custGuanzhuDto) {
        if (custGuanzhuDto.getType() == 1) {
            CustGuanzhuEntity custGuanzhuEntity = new CustGuanzhuEntity();
            custGuanzhuEntity.setAddTime(new Date());
            custGuanzhuEntity.setCustId(custId);
            custGuanzhuEntity.setCId(custGuanzhuDto.getCustId());
            custGuanzhuDao.insert(custGuanzhuEntity);
        } else if (custGuanzhuDto.getType() == 2) {
            custGuanzhuDao.deleteById(custId, custGuanzhuDto.getCustId());
        }
    }

}